package com.liangsui.cmall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.liangsui.cmall.auth.feign.MemberFeignService;
import com.liangsui.cmall.auth.feign.ThirdPartFeignService;
import com.liangsui.cmall.auth.vo.UserLoginVo;
import com.liangsui.cmall.auth.vo.UserRegisterVo;
import com.liangsui.common.constant.AuthServerConstant;
import com.liangsui.common.exception.BizCodeEnume;
import com.liangsui.common.utils.R;
import com.liangsui.common.vo.MemberRespVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {
    @Autowired
    private ThirdPartFeignService thirdPartFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute == null) {
            return "login";
        } else {
            return "redirect:http://cmall.com";
        }
    }

    /**
     * 发送验证码
     * @return
     */
    @ResponseBody
    @PostMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone) {
        //TODO 接口防刷
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (StringUtils.hasLength(redisCode)) {
            Long createdTime = Long.parseLong(redisCode.split("_")[1]);
            //防止同一个手机号在60秒再次发送验证码
            if (System.currentTimeMillis() - createdTime < 60000) {
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        //验证码再次检验 key-phone，value-code  sms:code:12356965584->12345
        String codeWithTime = UUID.randomUUID().toString().substring(0, 5) + "_" + System.currentTimeMillis();

        String code = codeWithTime.split("_")[0];
        //redis缓存验证码
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, codeWithTime, 5, TimeUnit.MINUTES);
        thirdPartFeignService.sendCode(phone, code);
        return R.ok();
    }

    @PostMapping("/register")
    public String register(@Valid UserRegisterVo vo, BindingResult result, RedirectAttributes attributes) {
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(
                    Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage
                    ));
            attributes.addFlashAttribute("errors", errors);
            //校验出错回到注册页
            return "redirect:http://auth.cmall.com/reg.html";
        }
        //真正注册
        //校验验证码
        String code = vo.getCode();
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (StringUtils.hasLength(s)) {
            if (code.equals(s.split("_")[0])) {
                //删除验证码
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                //验证码通过
                R r = memberFeignService.register(vo);
                if (r.getCode() == 0) {
                    //注册成功回到登录页
                    return "redirect:http://auth.cmall.com/login.html";
                } else {
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", r.getData("msg", new TypeReference<String>(){}));
                    attributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.cmall.com/reg.html";
                }
            } else {
                return registerFail(attributes);
            }
        } else {
            return registerFail(attributes);
        }
    }

    private String registerFail(RedirectAttributes attributes) {
        Map<String, String> errors = new HashMap<>();
        errors.put("code", "验证码错误");
        attributes.addFlashAttribute("errors", errors);
        //校验出错回到注册页
        return "redirect:http://auth.cmall.com/reg.html";
    }

    @PostMapping("/login")
    private String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session) {
        R r = memberFeignService.login(vo);
        if (r == null) {
            return loginFail(redirectAttributes, r);
        } else {
            if (r.getCode() == 0) {
                MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {
                });
                session.setAttribute(AuthServerConstant.LOGIN_USER, data);
                return "redirect:http://cmall.com";
            } else {
                return loginFail(redirectAttributes, r);
            }
        }
    }

    private String loginFail(RedirectAttributes redirectAttributes, R r) {
        Map<String, String> errors = new HashMap<>();
        errors.put("msg", r.getData("msg", new TypeReference<String>() {
        }));
        redirectAttributes.addFlashAttribute("errors", errors);
        return "redirect:http://auth.cmall.com/login.html";
    }
}
